package com.zst.sw.server.network;

import com.zst.sw.server.configuration.props.ConfigProperties;
import com.zst.sw.server.exception.GrpcServerException;
import io.grpc.Grpc;
import io.grpc.InsecureServerCredentials;
import io.grpc.Server;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;

@Slf4j
@AllArgsConstructor
public class GrpcServer implements ApplicationListener<ApplicationReadyEvent> {
    private ConfigProperties config;
    private TraceSegmentReportServiceHandler handler;

    public void start() {
        try {
            Server server = Grpc.newServerBuilderForPort(config.getPort(), InsecureServerCredentials.create())
                    .addService(handler)
                    .build()
                    .start();
        } catch (Exception e) {
            throw new GrpcServerException("grpc server start error", e);
        }
    }

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        start();
    }
}
